package com.jingzhe.biz.sys.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.jingzhe.biz.sys.domain.SysMenu;
import com.jingzhe.biz.sys.persistence.SysMenuMapper;
import com.jingzhe.biz.sys.service.ISysMenuService;

@Service
public class SysMenuServiceImpl implements ISysMenuService {
    @Resource
    private SysMenuMapper sysMenuMapper;
    
    @Override
    public Map<String, SysMenu> selectAllByParentId(Integer parentId, Map<String, SysMenu> sysMenuMap) {
        List<SysMenu> sysMenuChildList = sysMenuMapper.selectByParentId(parentId);
        
        if (!sysMenuChildList.isEmpty()) {
            for (SysMenu child : sysMenuChildList) {
                sysMenuMap.put("" + child.getId(), child);
                selectAllByParentId(child.getId(), sysMenuMap);
            }  
        }
        return sysMenuMap;
    }

    @Override
    public List<SysMenu> selectByParentId(Integer parentId) {
        return sysMenuMapper.selectByParentId(parentId);
    }

    @Override
    public SysMenu selectById(Integer menuId) {
        return sysMenuMapper.selectById(menuId);
    }

	@Override
	public int insertMenu(SysMenu sysMenu) {
		Date now = new Date();
		sysMenu.setBranchFlag((byte) 0);
		sysMenu.setCreateDate(now);
		sysMenu.setUpdateDate(now);
		
		SysMenu parentMenu = sysMenuMapper.selectById(sysMenu.getParentId());
		if (parentMenu != null) {
			sysMenu.setParentIds(parentMenu.getParentIds() + "," + sysMenu.getParentId());
		}
		sysMenuMapper.insert(sysMenu);
		
		if (parentMenu.getBranchFlag() == 0) {
			SysMenu parentMenuV2 = new SysMenu();
			parentMenuV2.setId(parentMenu.getId());
			parentMenuV2.setBranchFlag((byte) 1);
			sysMenuMapper.updateById(parentMenuV2);
		}
		return sysMenu.getId();
	}

	@Override
	public void updateMenu(SysMenu sysMenu) {
		Date now = new Date();
		sysMenu.setUpdateDate(now);
		sysMenuMapper.updateById(sysMenu);
	}

	@Override
	public void deleteMenu(Integer menuId, Integer userId) {
		//1.删除当前菜单
		SysMenu sysMenu = new SysMenu();
		Date now = new Date();
		sysMenu.setId(menuId);
		sysMenu.setUpdateDate(now);
		sysMenu.setUpdateBy(userId);
		sysMenu.setDelFlag((byte) 1);
		sysMenuMapper.updateById(sysMenu);
		
		//2.删除所有下级菜单
		sysMenuMapper.deleteAllChidlds(menuId, userId);
		
		//3.修改上级跟节点标识
		Integer parentId = sysMenuMapper.selectById(menuId).getParentId();
		List<SysMenu> brotherList = sysMenuMapper.selectByParentId(parentId);
		if (brotherList.size() == 0) {
			SysMenu sysMenuV2 = new SysMenu();
			sysMenuV2.setId(parentId);
			sysMenuV2.setUpdateDate(now);
			sysMenuV2.setUpdateBy(userId);
			sysMenuV2.setBranchFlag((byte) 0);
			sysMenuMapper.updateById(sysMenuV2);
		}
	}
    
    

}
